#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试批量压缩问题
"""

import sys
import os
import subprocess

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

def create_simple_test_video():
    """创建一个简单的测试视频"""
    print("创建简单测试视频...")
    
    try:
        cmd = [
            'ffmpeg', '-f', 'lavfi', '-i', 'testsrc=duration=5:size=320x240:rate=30',
            '-c:v', 'libx264', '-preset', 'ultrafast', '-crf', '23',
            'debug_test.mp4', '-y'
        ]
        
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode == 0 and os.path.exists('debug_test.mp4'):
            file_size = os.path.getsize('debug_test.mp4')
            print(f"✅ 测试视频创建成功: debug_test.mp4 ({file_size} 字节)")
            return True
        else:
            print(f"❌ 测试视频创建失败: {result.stderr}")
            return False
            
    except Exception as e:
        print(f"❌ 创建测试视频时出错: {str(e)}")
        return False

def debug_batch_compression():
    """调试批量压缩"""
    print("\n调试批量压缩...")
    
    if not os.path.exists('debug_test.mp4'):
        print("❌ 测试视频不存在")
        return False
    
    try:
        from core.compressor import VideoCompressor
        
        compressor = VideoCompressor()
        
        # 设置详细的进度回调
        def debug_progress_callback(progress, message):
            print(f"[DEBUG] 进度: {progress:.1f}% - {message}")
        
        compressor.set_progress_callback(debug_progress_callback)
        
        # 测试批量压缩
        input_files = [os.path.abspath("debug_test.mp4")]
        output_dir = os.getcwd()
        
        print(f"输入文件: {input_files}")
        print(f"输出目录: {output_dir}")
        
        # 检查输出路径生成
        test_output_path = compressor.generate_output_path(input_files[0], output_dir)
        print(f"预期输出路径: {test_output_path}")
        
        print("\n开始批量压缩...")
        
        result = compressor.compress_batch(input_files, output_dir, "medium_quality")
        
        print(f"\n批量压缩结果:")
        print(f"总文件数: {result['total_files']}")
        print(f"成功: {result['successful']}")
        print(f"失败: {result['failed']}")
        
        print("\n详细结果:")
        for item in result['results']:
            print(f"文件: {item['file']}")
            print(f"状态: {item['status']}")
            if item['status'] == 'failed':
                print(f"错误: {item['error']}")
            print()
        
        return result['successful'] > 0
        
    except Exception as e:
        print(f"❌ 批量压缩调试失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return False

def test_single_compression():
    """测试单文件压缩作为对比"""
    print("\n测试单文件压缩...")
    
    if not os.path.exists('debug_test.mp4'):
        print("❌ 测试视频不存在")
        return False
    
    try:
        from core.compressor import VideoCompressor
        
        compressor = VideoCompressor()
        
        def progress_callback(progress, message):
            print(f"[单文件] 进度: {progress:.1f}% - {message}")
        
        compressor.set_progress_callback(progress_callback)
        
        input_file = os.path.abspath("debug_test.mp4")
        output_file = os.path.abspath("debug_test_single.mp4")
        
        print(f"输入: {input_file}")
        print(f"输出: {output_file}")
        
        result = compressor.compress_video(input_file, output_file, "medium_quality")
        
        if result['success']:
            print("✅ 单文件压缩成功")
            return True
        else:
            print("❌ 单文件压缩失败")
            return False
            
    except Exception as e:
        print(f"❌ 单文件压缩失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return False

def main():
    """主函数"""
    print("=" * 50)
    print("批量压缩问题调试")
    print("=" * 50)
    
    # 创建测试视频
    if not create_simple_test_video():
        return
    
    # 测试单文件压缩
    single_success = test_single_compression()
    
    # 调试批量压缩
    batch_success = debug_batch_compression()
    
    print("\n" + "=" * 50)
    print("调试结果:")
    print(f"单文件压缩: {'✅ 成功' if single_success else '❌ 失败'}")
    print(f"批量压缩: {'✅ 成功' if batch_success else '❌ 失败'}")
    
    # 清理文件
    test_files = ['debug_test.mp4', 'debug_test_single.mp4', 'debug_test_compressed.mp4']
    for file in test_files:
        if os.path.exists(file):
            try:
                os.remove(file)
                print(f"清理: {file}")
            except:
                pass

if __name__ == "__main__":
    main()
